package com.event.management.frontend.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.event.management.frontend.common.Result;
import com.event.management.frontend.domain.Event;
import com.event.management.frontend.dto.CategoryDTO;
import com.event.management.frontend.dto.EventDetailDTO;
import com.event.management.frontend.dto.EventListDTO;
import com.event.management.frontend.dto.EventQueryParam;
import com.event.management.frontend.dto.TicketTypeDTO;
import com.event.management.frontend.mapper.EventMapper;
import com.event.management.frontend.mapper.TicketMapper;
import com.event.management.frontend.service.EventService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 活动服务实现类
 */
@Service
@RequiredArgsConstructor
public class EventServiceImpl implements EventService {

    private final EventMapper eventMapper;
    private final TicketMapper ticketMapper;

    /**
     * 活动分类与标签映射（模拟数据）
     */
    private static final Map<String, List<String>> CATEGORY_TAGS = new HashMap<>();

    static {
        CATEGORY_TAGS.put("音乐", Arrays.asList("演唱会", "音乐节", "古典音乐"));
        CATEGORY_TAGS.put("体育", Arrays.asList("跑步", "足球", "篮球", "健身"));
        CATEGORY_TAGS.put("亲子", Arrays.asList("亲子", "教育", "书籍", "动漫"));
        CATEGORY_TAGS.put("文化", Arrays.asList("展览", "博物馆", "讲座", "戏剧"));
        CATEGORY_TAGS.put("休闲", Arrays.asList("户外", "旅行", "摄影", "聚会"));
    }

    @Override
    @Cacheable(value = "eventCache", key = "'eventList_' + #param.toString()", unless = "#result == null || #result.records.isEmpty()")
    public Result.Page<EventListDTO> getEventList(EventQueryParam param) {
        Page<EventListDTO> page = new Page<>(param.getPageNum(), param.getPageSize());
        page = (Page<EventListDTO>) eventMapper.selectEventList(page, param);
        
        // 处理标签字符串为列表
        page.getRecords().forEach(event -> {
            String tagString = event.getTags() != null ? String.valueOf(event.getTags()) : "";
            if (StringUtils.hasText(tagString)) {
                event.setTags(Arrays.asList(tagString.split(",")));
            } else {
                event.setTags(new ArrayList<>());
            }
        });
        
        Result.Page<EventListDTO> result = new Result.Page<>();
        result.setRecords(page.getRecords());
        result.setTotal(page.getTotal());
        return result;
    }

    @Override
    @Cacheable(value = "eventCache", key = "'eventDetail_' + #id", unless = "#result == null")
    public EventDetailDTO getEventDetail(Long id) {
        // 增加浏览量
        eventMapper.incrementViewCount(id);
        
        // 查询活动基本信息
        Event event = eventMapper.selectById(id);
        if (event == null) {
            return null;
        }
        
        EventDetailDTO detailDTO = new EventDetailDTO();
        BeanUtils.copyProperties(event, detailDTO);
        
        // 处理标签
        if (event.getTags() != null && !event.getTags().isEmpty()) {
            detailDTO.setTags(Arrays.asList(event.getTags().split(",")));
        } else {
            detailDTO.setTags(new ArrayList<>());
        }
        
        // 查询票种信息
        List<TicketTypeDTO> tickets = ticketMapper.selectTicketsByEventId(id);
        detailDTO.setTicketTypes(tickets);
        
        return detailDTO;
    }

    @Override
    @Cacheable(value = "eventCache", key = "'eventTickets_' + #eventId", unless = "#result == null || #result.isEmpty()")
    public List<TicketTypeDTO> getEventTickets(Long eventId) {
        return ticketMapper.selectTicketsByEventId(eventId);
    }

    @Override
    @Cacheable(value = "eventCache", key = "'recommendEvents_' + #limit", unless = "#result == null || #result.isEmpty()")
    @CacheEvict(value = "eventCache", key = "'recommendEvents_' + #limit", condition = "#result != null && !#result.isEmpty()")
    public List<EventListDTO> getRecommendEvents(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 4; // 默认返回4条
        }
        
        List<EventListDTO> events = eventMapper.selectHotEvents(limit);
        
        // 处理标签
        events.forEach(event -> {
            String tagString = event.getTags() != null ? String.valueOf(event.getTags()) : "";
            if (StringUtils.hasText(tagString)) {
                event.setTags(Arrays.asList(tagString.split(",")));
            } else {
                event.setTags(new ArrayList<>());
            }
        });
        
        return events;
    }

    @Override
    @Cacheable(value = "eventCache", key = "'categories'", unless = "#result == null || #result.isEmpty()")
    public List<CategoryDTO> getCategories() {
        // 将静态的分类和标签数据转换为DTO
        return CATEGORY_TAGS.entrySet().stream()
                .map(entry -> {
                    CategoryDTO categoryDTO = new CategoryDTO();
                    categoryDTO.setName(entry.getKey());
                    categoryDTO.setTags(entry.getValue());
                    return categoryDTO;
                })
                .collect(Collectors.toList());
    }
} 